package com.shwread.android.ui.widget;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.activity.OrderDetailActivity;
import com.shwread.android.qysw10000152.R;
import com.shwread.android.ui.customview.MyListView;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.refresh.PullToRefreshScrollView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.http.ActionHelp;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.util.Logger;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import logic.bean.OrderDetailColum;
import logic.bean.OrderDetailInfo;
import logic.constants.DefaultConsts;
import logic.util.MoneyUtil;
import logic.util.NetworkUtil;
import logic.util.PicassoUtil;
import logic.util.Utils;


/**
 * 待评价页面
 * 
 * @author zhangnannan
 */
public class MyGoodsNoCommentView
        extends
        LinearLayout
{
	
	private Context                 mContext;
	private MyListView              mContentListView;
	private List<OrderDetailColum>  goodsList          = new ArrayList<OrderDetailColum>(); //单个订单商品详情
	private List<OrderDetailInfo>   orderList          = new ArrayList<OrderDetailInfo>(); //所有订单信息
	private PullToRefreshScrollView psView;
	private ContentAdapter          mContentAdapter;
	private SubOrderAdapter         subOrderAdapter;
	
	private int                     flag               = 0;
	private int                     pagelength         = 1;                                //默认一页显示多少条数据
	private long                    lastOrderCreatTime = 0L;                               //当前页最后一条订单的创建时间
	private int                     currentPageLength  = 1;                                //此次接口请求回来的数据长度                                                                                
	private LoadingView             loadingView;
	
	public MyGoodsNoCommentView(Context context) {
		super(context);
		mContext = context;
		initWithContext(context);
	}
	
	@SuppressLint ("NewApi")
    public MyGoodsNoCommentView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		initWithContext(context);
	}
	
	public MyGoodsNoCommentView(Context context, AttributeSet attrs) {
		super(context, attrs);
		initWithContext(context);
	}
	
	private void initWithContext(Context context) {
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		LinearLayout containerView = (LinearLayout) LayoutInflater.from(context).inflate(R.layout.my_goods_list_lay, null);
		psView = (PullToRefreshScrollView) containerView.findViewById(R.id.my_goods_psview);
		
		View mListView = (View) LayoutInflater.from(context).inflate(R.layout.my_goods_list, null);
		mContentListView = (MyListView) mListView.findViewById(R.id.my_goods_listview);
		
		//		subOrderAdapter = new SubOrderAdapter();
		mContentAdapter = new ContentAdapter();
		mContentListView.setAdapter(mContentAdapter);
		psView.addView(mListView);
		
		loadingView = (LoadingView) containerView.findViewById(R.id.my_goods_loading_view);
		loadingView.setLoadingAnim(R.anim.home_progress);
		loadingView.setVisibility(View.GONE);
		//		loadingView.changeLoadingStatus(0);
		
		addView(containerView, lp);
		
		getData(0);
		
		PullToRefreshUtil.initLabel(mContext, psView);
		psView.setOnRefreshListener(new OnRefreshListener<ScrollView>()
		{
			
			@Override
			public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
				if (psView.isHeaderShown())
				{ //下拉刷新
					refresh();
				}
				else if (psView.isFooterShown())
				{ //上拉加载
					loadMore();
				}
			}
			
		});
		
	}
	
	/**
	 * 上拉加载更多
	 */
	private void loadMore() {
		//				Utils.showToast(mContext, "上拉加载更多");
		if (orderList.size() > 0)
		{
			lastOrderCreatTime = orderList.get(orderList.size() - 1).getCreateTime();
		}
		else
		{
			lastOrderCreatTime = 0L;
		}
		if (currentPageLength < pagelength)
		{
			PullToRefreshUtil.setLoadLabel(psView, "没有更多数据了");
			psView.onRefreshComplete();
		}
		else
		{
			
			getData(2);
		}
	}
	
	/**
	 * 下拉刷新
	 */
	private void refresh() {
		//				Utils.showToast(mContext, "下拉刷新");
		lastOrderCreatTime = 0L;
		getData(1);
	}
	
	/**
	 * 关闭加载动画
	 * int flag,int statue
	 * flag 0首次加载，1为下拉刷新，2为上拉加载更多
	 * status 0:加载中，1：加载空白，2 为加载成功 -1：加载失败
	 */
	private void stopLoading(int flag, int status) {
		if (flag == 0)
		{
			loadingView.changeLoadingStatus(status);
		}
		else
		{
			psView.onRefreshComplete();
		}
	}
	
	/**
	 * 获取数据
	 */
	private void getData(int a) {
		this.flag = a;
		if (NetworkUtil.isNetAvailable(mContext))
		{
			ActionHelp.qryUserOrders(mContext, pagelength, lastOrderCreatTime, "", new getDataListener());
		}
		else
		{
			new NoNetDialog(mContext);
		}
		
	}
	
	private class getDataListener
	        extends
	        ObjectHttpResponseHandler<List<OrderDetailInfo>>
	{
		
		@Override
		public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
			Logger.e("错误状态妈--------" + Integer.toString(statusCode));
			Logger.e(throwable);
			currentPageLength = 4;
			if (statusCode < 1000)
			{
				
				Utils.ToastShow(mContext, "网络错误");
			}
			else
			{
				Utils.ToastShow(mContext, "请求出错");
			}
			stopLoading(flag, -1);
			
		}
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, List<OrderDetailInfo> object, String responseString) {
			System.out.println("xxxxxxxxxxxxxxxxxxx_" + responseString);
			Logger.i(responseString);
			if (object.size() > 0)
			{
				currentPageLength = object.size();
				//关闭加载动画
				stopLoading(flag, 2);
				//清空list
				if (flag != 2)
				{
					if (orderList.size() > 0) orderList.clear();
					orderList.addAll(object);
				}
				else
				{
					orderList.addAll(object);
				}
				
				mContentAdapter.notifyDataSetChanged();
			}
			else
			{
				stopLoading(flag, 1);
				currentPageLength = 0;
			}
		}
		
		@Override
		public Type getType() {
			return new TypeToken<List<OrderDetailInfo>>()
			{
			}.getType();
		}
		
	}
	
	/**************** 全部订单的 Adapter ***********************/
	
	private class ContentAdapter
	        extends
	        BaseAdapter
	{
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return orderList.size() <= 0 ? 0 : orderList.size();
			//			return (goodsList==null||goodsList.size()==0)?0:goodsList.size();
		}
		
		@Override
		public Object getItem(int position) {
			return (orderList == null || orderList.size() == 0) ? null : orderList.get(position);
		}
		
		@Override
		public long getItemId(int position) {
			
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null)
			{
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.my_goods_list_item, null);
				viewHolder.tvOrderNumber = (TextView) convertView.findViewById(R.id.goods_detail_item_top_order_number);
				viewHolder.tvOrderState = (TextView) convertView.findViewById(R.id.goods_detail_item_top_order_state);
				viewHolder.lvOrderView = (MyListView) convertView.findViewById(R.id.my_goods_list_item_listview);
				viewHolder.tvGoodsTotalPrice = (TextView) convertView.findViewById(R.id.goods_detail_item_bottom_total_pay_tv);
				viewHolder.butGoodsClose = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_close_btn);
				viewHolder.butGoodsComment = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_comment_btn);
				viewHolder.butGoodsDeliver = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_deliver_btn);
				viewHolder.butGoodsPay = (Button) convertView.findViewById(R.id.goods_detail_item_bottom_pay_btn);
				viewHolder.butGoodsComment.setVisibility(View.GONE);
				convertView.setTag(viewHolder);
			}
			else
			{
				viewHolder = (ViewHolder) convertView.getTag();
			}
			
			final OrderDetailInfo orderDetailInfo = (OrderDetailInfo) getItem(position);
			viewHolder.tvOrderNumber.setText("订单号:" + orderDetailInfo.getOrderSerial());
			viewHolder.tvOrderNumber.setVisibility(View.VISIBLE);
			viewHolder.tvGoodsTotalPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(orderDetailInfo.getTotalMoney(), 100)));
			//设置状态
			viewHolder.tvOrderState.setVisibility(View.VISIBLE);
			
			viewHolder.tvOrderState.setText("待评价");
			viewHolder.butGoodsClose.setVisibility(View.VISIBLE);
			viewHolder.butGoodsPay.setVisibility(View.VISIBLE);
			viewHolder.butGoodsDeliver.setVisibility(View.GONE);
			
			viewHolder.butGoodsClose.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					Utils.showToast(mContext, "您点击了关闭");
				}
			});
			
			viewHolder.butGoodsComment.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					Utils.showToast(mContext, "您点击了评论");
				}
			});
			
			viewHolder.butGoodsDeliver.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					Utils.showToast(mContext, "您点击了物流");
					//					Intent intent = new Intent(mContext, GoodsOrderDeliverDetailActivity.class);
				}
			});
			
			viewHolder.butGoodsPay.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v) {
					Utils.showToast(mContext, "您点击了付款");
				}
			});
			
			SubOrderAdapter subOrderAdapter = new SubOrderAdapter(orderDetailInfo);
			
			viewHolder.lvOrderView.setAdapter(subOrderAdapter);
			subOrderAdapter.notifyDataSetChanged();
			
			viewHolder.lvOrderView.setOnItemClickListener(new OnItemClickListener()
			{
				
				@Override
				public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
					OrderDetailInfo Info = orderDetailInfo;
					Intent intent = new Intent(mContext, OrderDetailActivity.class);
					intent.putExtra(DefaultConsts.ORDER_DETAIL_FROM_TYPE, DefaultConsts.ORDER_DETAIL_STATE_ALL);
					intent.putExtra(DefaultConsts.ORDER_DETAIL_ORDER_ID, Info.getOrderId());
					mContext.startActivity(intent);
					
				}
			});
			return convertView;
		}
		
	}
	
	private class ViewHolder
	{
		private TextView   tvOrderNumber, tvOrderState;
		private MyListView lvOrderView;
		private TextView   tvGoodsTotalPrice;
		private Button     butGoodsDeliver;
		private Button     butGoodsComment;
		private Button     butGoodsClose;
		private Button     butGoodsPay;
	}
	
	/******************* 单个订单的详情 **************************************/
	
	class SubOrderAdapter
	        extends
	        BaseAdapter
	{
		
		private OrderDetailInfo orderInfo;
		
		/**
         * 
         */
		public SubOrderAdapter(OrderDetailInfo info) {
			this.orderInfo = info;
		}
		
		@Override
		public int getCount() {
			//			return 3;
			return (orderInfo == null || orderInfo.getGoodsList().size() == 0) ? 0 : orderInfo.getGoodsList().size();
		}
		
		@Override
		public Object getItem(int position) {
			
			return (orderInfo.getGoodsList() == null || orderInfo.getGoodsList().size() == 0) ? null : orderInfo.getGoodsList().get(position);
		}
		
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			SubOrderViewHolder holder;
			if (convertView == null)
			{
				holder = new SubOrderViewHolder();
				convertView = LayoutInflater.from(mContext).inflate(R.layout.goods_detail_item, null);
				holder.ivGoodsCover = (ImageView) convertView.findViewById(R.id.goods_detail_item_image);
				holder.tvGoodsIntro = (TextView) convertView.findViewById(R.id.goods_detail_item_name_tv);
				holder.tvGoodsPrice = (TextView) convertView.findViewById(R.id.goods_detail_item_original_price_tv);
				holder.tvGoodsCount = (TextView) convertView.findViewById(R.id.goods_detail_item_original_count_tv);
				holder.tvGoodsSort = (TextView) convertView.findViewById(R.id.goods_detail_item_classify_tv);
				
				convertView.setTag(holder);
			}
			else
			{
				holder = (SubOrderViewHolder) convertView.getTag();
			}
			
			OrderDetailColum orderDetailColum = (OrderDetailColum) getItem(position);
			if (Utils.isEmpty(orderDetailColum.getCoverUrl()))
			{//设置默认图片
			
			}
			else
			{
//				holder.ivGoodsCover.setImageUrl(orderDetailColum.getCoverUrl());
				PicassoUtil.load(mContext, orderDetailColum.getCoverUrl(), R.drawable.atlas_default_img, holder.ivGoodsCover);
			}
			holder.tvGoodsIntro.setText(orderDetailColum.getTitle());
			holder.tvGoodsPrice.setText(" ¥" + Utils.getMoneyFormat(MoneyUtil.divide(orderDetailColum.getSalePrice(), 100)));
			holder.tvGoodsCount.setText("x " + orderDetailColum.getBuyNum());
			Map map = new HashMap();
			map.putAll(orderDetailColum.getSkuProp());
			
			StringBuilder str = new StringBuilder();
			if (orderDetailColum.getSkuProp() != null && orderDetailColum.getSkuProp().size() > 0)
			{
				for (Entry<String, String> entry : orderDetailColum.getSkuProp().entrySet())
				{
					if (str.length() > 0)
					{
						str.append(",");
					}
					str.append(entry.getKey() + ": ");
					str.append(entry.getValue());
				}
			}
			holder.tvGoodsSort.setText(str);
			
			return convertView;
		}
	}
	
	class SubOrderViewHolder
	{
		private TextView       tvGoodsIntro;
		private TextView       tvGoodsPrice;
		private TextView       tvGoodsCount;
		private TextView       tvGoodsSort;
		private ImageView ivGoodsCover;
	}
	
}
